package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.data.GeoData;
import admin.forms.GeoForm;

import debugs.GeoDebug;

import models.GeoModel;

public class EditGeoServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String path = ((HttpServletRequest) request).getRequestURI();
		String geoId = "";
		try {
			geoId = URLDecoder.decode(path.replaceAll("/admin/geo/edit/", ""),"UTF-8");
		} catch (Exception e) {
			response.sendRedirect("/admin/geo/list");
		}
		
		TreeMap check = new TreeMap();
		GeoData geoData = new GeoData();
		GeoModel geo = geoData.getGeo(geoId);
		
		ArrayList<GeoModel> geos = geoData.getAll();
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("geo", geo);
		request.setAttribute("geos", geos);
		try {
			request.getRequestDispatcher("/admin/pages/form_geo.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String path = ((HttpServletRequest) request).getRequestURI();
		String geoId = "";
		try {
			geoId = URLDecoder.decode(path.replaceAll("/admin/geo/edit/", ""),"UTF-8");
		} catch (Exception e) {
			response.sendRedirect("/admin/geo/list");
		}
		
		TreeMap check = new TreeMap();
		GeoData geoData = new GeoData();
		GeoModel geo = geoData.getGeo(geoId);
		
		GeoForm geoForm = new GeoForm();
		TreeMap form = (TreeMap) geoForm.checkValidFormEdit(request, geo);
		geo = (GeoModel) form.get("geo");
		check = (TreeMap) form.get("checkValid");
		
		if (check.size() == 0) {
			geoData.insert(geo);
			request.setAttribute("success", "Bạn đã thay đổi thành công.");
		}
		
		ArrayList<GeoModel> geos = geoData.getAll();
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("geo", geo);
		request.setAttribute("geos", geos);
		try {
			request.getRequestDispatcher("/admin/pages/form_geo.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
